let WebIM = require('./utils/WebIM.js').default

App({
  onLaunch() {
    let that = this
    let page = 'pages/chat/chat'

    //判断机型(适配iphoneX)
    wx.getSystemInfo({
      success: (res) => {
        if (res.model.search('iPhone X') != -1) {
          this.globalData.isIphoneX = true
        }
      }
    })

    // 获取openid
    that.getOpenId()  

    // 环信的各种监听
    WebIM.conn.listen({
      onOpened () {
        WebIM.conn.setPresence()
      },
      onAudioMessage (message) {
        if (message) {
          if (page) {
            page.receiveMsg(message, 'audio')
          } else {
            var chatMsg = that.globalData.chatMsg || []
            var value = WebIM.parseEmoji(message.data.replace(/\n/mg, ''))
            var time = WebIM.time()
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              username: message.from,
              yourname: message.from,
              msg: {
                type: 'audio',
                data: value
              },
              style: '',
              time: time,
              mid: 'audio' + message.id
            }
            console.log("Audio msgData: ", msgData);
            chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
            var num = wx.getStorageSync(msgData.yourname + message.to + '-num') || 0;
            wx.setStorage({
              key: msgData.yourname + 'and' + message.to + '-num',
              data: ++num,
              success () {
                //console.log('success')
              }
            })
            chatMsg.push(msgData)
            wx.setStorage({
              key: msgData.yourname + 'and' + message.to,
              data: chatMsg,
              success () {
                //console.log('success')
              }
            })
          }
        }
      }, 
      onTextMessage (message) {
        if (message) {
          if (page) {
            page.receiveMsg(message, 'txt')
          } else {
            // 谁给我发送离线消息，就将对方id添加到本地缓存中
            let member = wx.getStorageSync('member')
            let yourname = message.from
            if (member === '') {
              wx.setStorage({
                key: 'member',
                data: [{ name: yourname }]
              })
            } else {
              let result = member.filter(item => {
                return item.name === yourname
              })
              if (result.length === 0) {
                member.push({ name: yourname })
                wx.setStorage({
                  key: 'member',
                  data: member
                })
              }
            }

            var chatMsg = that.globalData.chatMsg || []
            var value = WebIM.parseEmoji(message.data.replace(/\n/mg, ''))
            var time = WebIM.time()
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              username: message.from,
              yourname: message.from,
              msg: {
                type: 'txt',
                data: value
              },
              style: '',
              time: time,
              mid: 'txt' + message.id
            }
            chatMsg = wx.getStorageSync(msgData.yourname + 'and' + message.to) || []
            var num = wx.getStorageSync(msgData.yourname + 'and' + message.to + '-num') || 0;
            wx.setStorage({
              key: msgData.yourname + 'and' + message.to + '-num',
              data: ++num,
              success () {
                //console.log('success')
              }
            }) 
            chatMsg.push(msgData)
            wx.setStorage({
              key: msgData.yourname + 'and' + message.to,
              data: chatMsg,
              success () {
                //console.log('success')
              }
            })
          }
        }
      },
      onEmojiMessage (message) {
        if (message) {
          if (page) {
            page.receiveMsg(message, 'emoji')
          } else {
            var chatMsg = that.globalData.chatMsg || []
            var time = WebIM.time()
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              username: message.from,
              yourname: message.from,
              msg: {
                type: 'emoji',
                data: message.data
              },
              style: '',
              time: time,
              mid: 'emoji' + message.id
            }
            msgData.style = ''
            chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
            var num = wx.getStorageSync(msgData.yourname + message.to + '-num') || 0;
            wx.setStorage({
              key: msgData.yourname + 'and' + message.to + '-num',
              data: ++num,
              success () {
                //console.log('success')
              }
            })
            chatMsg.push(msgData)
            //console.log(chatMsg)
            wx.setStorage({
              key: msgData.yourname + 'and' + message.to,
              data: chatMsg,
              success () {
                //console.log('success')
              }
            })
          }
        }
      },
      onPictureMessage (message) {
        if (message) {
          if (page) {
            page.receiveImage(message, 'img')
          } else {
            var chatMsg = that.globalData.chatMsg || []
            var time = WebIM.time()
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              username: message.from,
              yourname: message.from,
              msg: {
                type: 'img',
                data: message.url
              },
              style: '',
              time: time,
              mid: 'img' + message.id
            }
            msgData.style = ''
            chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
            var num = wx.getStorageSync(msgData.yourname + message.to + '-num') || 0;
            wx.setStorage({
              key: msgData.yourname + 'and' + message.to + '-num',
              data: ++num,
              success () {
                //console.log('success')
              }
            })
            chatMsg.push(msgData)
            wx.setStorage({
              key: msgData.yourname + 'and' + message.to,
              data: chatMsg,
              success () {
                //console.log('success')
              }
            })
          }
        }
      },
      onError (error) {
        // 16: server-side close the websocket connection
        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
          if (WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax) {
            return;
          }
          console.log('服务器端关闭websocket连接')
          return;
        }

        // 8: offline by multi login
        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
          console.log('你被人T了')
          return;
        }
      },
    })
  },
  // 获取openid
  getOpenId(){
    if (!wx.getStorageSync('openid')) {
      wx.login({
        success: res => {
          if (res.code) {
            wx.request({
              url: `https://api.weixin.qq.com/sns/jscode2session?appid=wxe3e84f2a9034d2c5&secret=f7d2ae535cf6cb1febfc07f931a157b9&js_code=${res.code}&grant_type=authorization_code`,
              success: res => {
                wx.setStorage({key: 'openid',data: res.data.openid})
              }
            })
          }
        }
      })
    }
  },

  globalData: {
    search: [], //搜索历史
    chatMsg: [],
    isIphoneX: false
  }
})